package cn.itsource.org.controller;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController //@Controller + @ResponseBody的结合体
@RequestMapping("/dept")
@Api(tags = "部门管理接口")
public class DepartmentController {
//        注入依赖
    @Autowired
    private IDepartmentService service;
//    查询全部
    @GetMapping
    @ApiOperation(value = "查询所有的部门")
    public AjaxResult list(){
        List<Department> all = service.findAll();
        return AjaxResult.createSuccess(all);
    }
//    新增修改
    @PostMapping
    @ApiOperation(value = "新增修改部门，新增没有id，修改有id")
    public AjaxResult saveOrUpdate(@Valid @RequestBody  Department department){
//        没有携带id说明为新增方法
        try {
            if (department.getId()==null){
                service.save(department);
            }else {
                service.update(department);
            }
            return AjaxResult.createSuccess();
        } catch (RuntimeException r) {
            return AjaxResult.createError(r.getMessage());
        }catch (Exception e){
                e.printStackTrace();
                return AjaxResult.createError();
            }

    }
//    删除
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除部门对象")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            service.delete(id);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError();
        }
    }
//    批量删除
@PostMapping("/batchRemove")
@ApiOperation(value = "根据id删除部门对象")
public AjaxResult deleteDatch(@RequestBody DepartmentQuery query){
   service.batchRemove(query);
   return AjaxResult.createSuccess();
}

    @PostMapping("/findPage")
    @ApiOperation(value = "分页查询")
    public PageList<Department> findPage(@RequestBody DepartmentQuery query){
        PageList<Department> page = service.findPage(query);
        return page;
    }
    /**
     * 查询所有
     * @return
     */
    @GetMapping("/tree")
    @ApiOperation(value = "查询部门无限极树") //swagger API
    public AjaxResult deptTree(){
        //查询
        List<Department> list = service.deptTree();
        //返回
        return AjaxResult.createSuccess(list);
    }

}
